<?php

class PostController extends BaseAdminController {

    public $menu = array(
        array('label' => 'Tạo mới tin tức', 'url' => array('post/create')),
        array('label' => 'Danh sách tin tức', 'url' => array('post/list'))
    );

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('index', 'list', 'create', 'update', 'delete', 'deleteImage', 'show', 'content', 'images', 'search'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $this->redirect(array('list'));
    }

    /**
     * List all model for search
     */
    public function actionSearch() {
        $postSearch = new Search;
        if (isset($_POST['Search'])) {
            $postSearch->attributes = $_POST['Search'];
            $keyWord = $postSearch->keyWord;
            $criteria = new CDbCriteria;
            $criteria->distinct = true;
            if (strlen($keyWord) > 0) {
                $searchCondition = '';
                if ($postSearch->searchByName) {
                    $searchCondition = 'd.title like :keyWord';
                }
                if ($postSearch->searchByContent) {
                    if ($searchCondition == '') {
                        $searchCondition = 'd.content like :keyWord';
                    } else {
                        $searchCondition = ' OR d.content like :keyWord';
                    }
                }
                if (!$postSearch->searchByName && !$postSearch->searchByContent) {
                    $searchCondition = 'd.title like :keyWord OR d.content like :keyWord';
                }
                if ($searchCondition != '') {
                    $searchCondition = ' AND (' . $searchCondition . ')';
                }
                $criteria->join = ' INNER JOIN post_detail d ON t.id=d.post_id ' . $searchCondition;
                $criteria->params = array(':keyWord' => '%' . $keyWord . '%');
            }
            $dataProvider = new CActiveDataProvider('Post', array(
                        'criteria' => $criteria,
                        'pagination' => array(
                            'pageSize' => 15,
                        ),
                    ));
            $postSearch = new Search;
            $this->render('list', array(
                'postSearch' => $postSearch,
                'dataProvider' => $dataProvider,
            ));
        }
    }

    /**
     * Manages all models.
     */
    public function actionList() {
        $postSearch = new Search;
        $dataProvider = new CActiveDataProvider('Post', array(
                    'pagination' => array(
                        'pageSize' => 15,
                    ),
                ));

        $this->render('list', array(
            'postSearch' => $postSearch,
            'dataProvider' => $dataProvider,
        ));
    }

    public function renameImage($imageName) {
        $newName = str_replace(array(' ', '\\', '/', ',', '(', ')', '-', '"', '\'', '%'), '_', $imageName);
        $newName = time().'_'. $newName;
        return $newName;
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $post = new Post;
        $postDetails = array();
        for ($i = 0; $i < 2; $i++) {
            $postDetail = new PostDetail;
            if ($i == 0) {
                $postDetail->language = 'vi';
            } else {
                $postDetail->language = 'en';
            }
            $postDetails[] = $postDetail;
        }
        $message = ''; //show message to view
        $postImage = new PostImage;
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Post']) && isset($_POST['PostDetail'])) {
            $post->attributes = $_POST['Post'];
            $valid = true;
            foreach ($postDetails as $i => $postDetail) {
                $postDetail->attributes = $_POST['PostDetail'][$i];
                $postDetails[$i] = $postDetail;
                $valid = $postDetail->validate() && $valid;
            }
            if ($valid) {
                //get images and check
                $canSave = true;
                $images = CUploadedFile::getInstancesByName('path');
                if (isset($images) && count($images) > 0) {
                    foreach ($images as $image => $pic) {
                        $imageName = $this->renameImage($pic->name);
                        /* if (PostImage::model()->existedImagePath('contents/uploads/images/post/' . $imageName)) {//check duplicated images path in database
                          $message = '"' . $imageName . '":' . Yii::t('post', 'existedImageName');
                          $canSave = false;
                          break;
                          } else { */
                        if (strlen('contents/uploads/images/post/' . $imageName) > 255) {//check length of images name
                            $message = '"' . $imageName . '":' . Yii::t('post', 'longImageName');
                            $canSave = false;
                            break;
                        }
                    }
                }
                if ($canSave) {
                    //begin upload images
                    $imagesName = array();
                    foreach ($images as $image => $pic) {
                        $imageName = $this->renameImage($pic->name);
                        $path = Yii::getPathOfAlias('webroot.contents.uploads.images.post') . DIRECTORY_SEPARATOR . $imageName;
                        if ($pic->saveAs($path)) {
                            $imagesName[] = $imageName;
                        }
                    }
                    //save model to database
                    try {
                        if ($post->save()) {
                            foreach ($postDetails as $postDetail) {
                                $postDetail->post_id = $post->id;
                                $postDetail->save();
                            }
                            //create list product images
                            foreach ($imagesName as $imageName) {
                                $postImage = new PostImage;
                                $postImage->post_id = $post->id;
                                $postImage->path = 'contents/uploads/images/post/' . $imageName;
                                $saved = $postImage->save();
                                if (!$saved) {//if saving fail, delete uploaded images
                                    $path = Yii::getPathOfAlias('webroot.contents.uploads.images.post') . DIRECTORY_SEPARATOR . $imageName;
                                    unlink($path);
                                }
                            }
                            Yii::app()->user->setFlash('message', Yii::t('post', 'successCreate'));
                            $this->refresh();
                            $this->redirect(array('create'));
                        }
                    } catch (Exception $ex) {
                        echo $ex->getMessage();
                        Yii::app()->user->setFlash('message', Yii::t('post', 'failCreate'));
                        $this->redirect(array('list'));
                    }
                }
            } else {
                $message = Yii::t('post', 'notValid');
            }
        }

        $this->render('create', array(
            'message' => $message,
            'post' => $post,
            'postDetails' => $postDetails,
            'postImage' => $postImage,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $message = '';
        $post = $this->loadModel($id);
        $postDetails = $post->postDetails;
        $postImage = new PostImage;


        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Post']) && isset($_POST['PostDetail'])) {
            $post->attributes = $_POST['Post'];
            $valid = true;
            foreach ($postDetails as $i => $postDetail) {
                $postDetail->attributes = $_POST['PostDetail'][$i];
                $postDetails[$i] = $postDetail;
                $valid = $postDetail->validate() && $valid;
            }
            if ($valid) {
                //get images and check
                $canSave = true;
                $images = CUploadedFile::getInstancesByName('path');
                if (isset($images) && count($images) > 0) {
                    foreach ($images as $image => $pic) {
                        $imageName = $this->renameImage($pic->name);
                        /* if (PostImage::model()->existedImagePath('contents/uploads/images/post/' . $imageName)) {//check duplicated images path in database
                          $message = '"' . $imageName . '":' . Yii::t('post', 'existedImageName');
                          $canSave = false;
                          break;
                          } else { */
                        if (strlen('contents/uploads/images/post/' . $imageName) > 255) {//check length of images name
                            $message = '"' . $imageName . '":' . Yii::t('post', 'longImageName');
                            $canSave = false;
                            break;
                        }
                    }
                }
                if ($canSave) {
                    //begin upload images
                    $imagesName = array();
                    foreach ($images as $image => $pic) {
                        $imageName = $this->renameImage($pic->name);
                        $path = Yii::getPathOfAlias('webroot.contents.uploads.images.post') . DIRECTORY_SEPARATOR . $imageName;
                        if ($pic->saveAs($path)) {
                            $imagesName[] = $imageName;
                        }
                    }
                    //save model to database
                    try {
                        if ($post->save()) {
                            foreach ($postDetails as $postDetail) {
                                $postDetail->save();
                            }
                            //create list product images
                            foreach ($imagesName as $imageName) {
                                $postImage = new PostImage;
                                $postImage->post_id = $post->id;
                                $postImage->path = 'contents/uploads/images/post/' . $imageName;
                                $saved = $postImage->save();
                                $er = $postImage->getErrors();
                                if (!$saved) {//if saving fail, delete uploaded images
                                    $path = Yii::getPathOfAlias('webroot.contents.uploads.images.post') . DIRECTORY_SEPARATOR . $imageName;
                                    unlink($path);
                                }
                            }
                            Yii::app()->user->setFlash('message', Yii::t('post', 'successUpdate'));
                            $this->redirect(array('list'));
                        }
                    } catch (Exception $ex) {
                        echo $ex->getMessage();
                        Yii::app()->user->setFlash('message', Yii::t('post', 'failUpdate'));
                        $this->redirect(array('list'));
                    }
                }
            } else {
                $message = Yii::t('post', 'notValid');
            }
        }

        $this->render('update', array(
            'message' => $message,
            'post' => $post,
            'postDetails' => $postDetails,
            'postImage' => $postImage,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, Yii::t('default', 'notValidWeb'));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $post = Post::model()->findByPk($id);
        if ($post === null)
            throw new CHttpException(404, Yii::t('default', 'notExistWeb'));
        return $post;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($post) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'post-form') {
            echo CActiveForm::validate($post);
            Yii::app()->end();
        }
    }

    /**
     * show image by path
     */
    public function actionShow($path) {
        $imagePath = $path;
        Yii::app()->clientScript->scriptMap['jquery.js'] = false;
        $this->renderPartial('viewImage', array('imagePath' => $imagePath,), false, true);
    }

    /**
     * action Content
     */
    public function actionContent($id) {
        $post = Post::model()->findByPk($id);
        $postDetails = $post->postDetails;
        Yii::app()->clientScript->scriptMap['jquery.js'] = false;
        $this->renderPartial('showContent', array('postDetails' => $postDetails,), false, true);
    }

    /**
     * action Images
     */
    public function actionImages($id) {
        $post = Post::model()->findByPk($id);
        $postImages = $post->postImages;
        Yii::app()->clientScript->scriptMap['jquery.js'] = false;
        $this->renderPartial('showImages', array('postImages' => $postImages,), false, true);
    }

    /**
     * Delete post image
     */
    public function actionDeleteImage($id) {
        $postImage = PostImage::model()->findByPk($id);
        $postImage->delete();
    }

}
